package com.trainoo.jwt;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.joda.time.LocalDateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * @Auther: zt
 * @Date: 2019/10/30 16:40
 * @Description:
 */
public class jwtDemo {

    private static final Logger LOG = LoggerFactory.getLogger(jwtDemo.class);
    private static final String SECRET = "+zqf97FD/xyzzyplugh42ploverFeeFieFoeFooxqjE=";

    public static void main(String[] args) {
        // String token = createToken();
        // LOG.info("token= {}", token);

        verifyToken("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoiMTIwIiwianRpIjoiNzIwMDAwMCIsIm5iZiI6MTU3NDQwNDI4OCwiZXhwIjoxNTc0NDExNDg4LCJpc3MiOiJ0eWMiLCJhdWQiOiJ0eWMifQ.e3VgvDHqmGz1PZmPUQyhk_vnXOC0Yilm7qhMUw9ujd8");
    }

    private static String createToken(){

        Map<String, Object> headerClaim = new HashMap<>();
        headerClaim.put("aaa", "AAA");
        headerClaim.put("bbb", "123456");

        return JWT.create()
                .withHeader(headerClaim)     // 添加头部
                .withClaim("name", "test")   // 添加自定义数据
                .withClaim("age", 20)
                .withExpiresAt(LocalDateTime.now().plusSeconds(10).toDate()) // 设置过期的日期,此处设置为10分钟后失效
                .sign(Algorithm.HMAC256(SECRET));
    }

    /**
     * verifier.verify(token) 方法：如果token失效，会抛出TokenExpiredException
     * JWT.decode(token) 方法：不会校验token是否失效，只做解密
     */
    private static void verifyToken(String token){

        JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
        try {
            // DecodedJWT decodedJWT = verifier.verify(token);
            DecodedJWT decodedJWT = JWT.decode(token);
            System.out.println(decodedJWT.getClaims());
            System.out.println(decodedJWT.getClaim("jti").asString());
            System.out.println(decodedJWT.getExpiresAt().before(LocalDateTime.now().toDate()));
            System.out.println(decodedJWT.getClaim("name").asString());
            System.out.println(decodedJWT.getClaim("age").asInt());
            System.out.println(decodedJWT.getHeaderClaim("aaa").asString());
            System.out.println(decodedJWT.getHeaderClaim("bbb").asString());

        } catch (JWTVerificationException e){
            LOG.error("验签错误", e);
        }
    }
}
